package com.bird.system.domain.menu

import com.bird.component.lang.common.exception.ServiceException
import com.bird.system.domain.menu.vo.UpdateMenuVO

class MenuHandler(private val menuRepository: MenuRepository) {

    /**
     * 添加菜单
     */
    fun addMenu(menuEntity: MenuEntity) {
        //标记新增
        menuEntity.toNew()
        //查询父级菜单
        val parentMenu = menuRepository.oneMenuById(menuEntity.parentId)
        //设置树路径
        parentMenu?.apply {
            //设置树路径
            menuEntity.treePath = "${this.treePath},${this.id}"
        }
        //保存菜单
        storeMenu(menuEntity)
    }

    /**
     * 删除菜单
     */
    fun deleteMenu(menuId: Long) {
        //标记删除
        val menuEntity = menuRepository.oneMenuById(menuId)
        menuEntity?.let {
            //标记删除
            it.toDelete()
            //保存菜单
            storeMenu(it)
        }
    }

    /**
     * 修改菜单
     */
    fun updateMenu(menuId: Long, updateMenuVO: UpdateMenuVO) {
        //获取菜单
        val menuEntity = menuRepository.oneMenuById(menuId) ?: throw ServiceException("菜单不存在")
        //修改菜单
        menuEntity.update(updateMenuVO)
        //查询父级菜单
        val parentMenu = menuRepository.oneMenuById(menuEntity.parentId)
        //设置树路径
        parentMenu?.apply {
            //设置树路径
            menuEntity.treePath = "${this.treePath},${this.id}"
        }
        //标记修改
        menuEntity.toUpdate()
        //保存菜单
        storeMenu(menuEntity)
    }

    /**
     * 保存菜单
     */
    private fun storeMenu(menuEntity: MenuEntity) {
        //对实体进行检验
        menuEntity.validate()
        //保存菜单
        menuRepository.save(menuEntity)
    }


}